#include "ImageManager.h"
#include <QPainter>
QImage gen(int width, int height, bool isSelected, const QString& text)
{
	QImage img(width, height, QImage::Format_RGBA8888);
	img.fill(QColor(Qt::transparent));

	QPainter painter(&img);
	painter.setRenderHints(QPainter::Antialiasing, true);
	QFont font;
	font.setPointSize(14);
	painter.setFont(font);

	QPen pen;
	pen.setColor(Qt::white);
	painter.setPen(pen);

	QTextOption option(Qt::AlignLeft | Qt::AlignTop);
	option.setWrapMode(QTextOption::WordWrap);

	int	   padding = 6;
	QRectF rect(padding, padding, width - padding, height - padding);
	painter.drawText(rect, text, option);

	if (isSelected)
	{
		pen.setColor(QColor(90, 255, 214));
		painter.setPen(pen);
	}
	pen.setWidth(2);
	painter.drawRect(1, 1, width - 2, height - 2);

	return img.mirrored();
}

ImageManager* ImageManager::getInstance()
{
	static ImageManager instance;
	return &instance;
}

ImageManager::ImageManager() { }

ImageManager::~ImageManager() { }
QImage ImageManager::genTextImage(int width, int height, bool isSelected, const QString& text)
{
	return gen(width, height, isSelected, text);
}
QImage ImageManager::genTextImageWithCache(int width, int height, bool isSelected, const QString& text)
{
	ImageInfo info;
	info.w			= width;
	info.h			= height;
	info.isSelected = isSelected;
	info.text		= text;
	auto it			= mImageCacheMap.find(info);
	if (it == mImageCacheMap.end())
	{
		auto img			 = gen(width, height, isSelected, text);
		mImageCacheMap[info] = img;
		const int cMaxCacheCount = 100;
		while (mImageCacheMap.size() > cMaxCacheCount)
		{
			mImageCacheMap.take(mImageCacheMap.keys().first());
		}
		return img;
	}
	else
	{
		return it.value();
	}
}

void ImageManager::clearCache()
{
	mImageCacheMap.clear();
}
